package py.com.fms.ven.session.transactions;

// External classes imports 
// Java Classes
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

// Seam Classes
import org.jboss.aspects.dbc.condition.parser.LoopExpression;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.richfaces.component.html.HtmlDatascroller;

import com.ibatis.sqlmap.client.SqlMapClient;

import javax.faces.application.FacesMessage;
import javax.faces.event.ActionEvent;
import javax.faces.validator.ValidatorException;

//project classes imports
import py.com.fms.ven.bean.SalesHeadBean;
import py.com.fms.ven.bean.SalesDetBean;
import py.com.fms.ven.bean.CommissionBean;
import py.com.fms.ven.bean.FeesToCustomersBean;
import py.com.fms.ven.bean.SellerBean;
import py.com.fms.ven.bean.ChargesTypeBean;
import py.com.fms.ven.bean.ReceiptChargesHeadBean;
import py.com.fms.ven.bean.ReceiptChargesDetBean;
import py.com.fms.ven.bean.ReceivedChecksBean;
import py.com.fms.ven.bean.CustomerBean;
import py.com.fms.ven.bean.PricesListHeadBean;
import py.com.fms.ven.bean.PricesListDetBean;

import py.com.fms.fms.bean.CurrencyBean;
import py.com.fms.fms.bean.EnterpriseBean;
import py.com.fms.fms.bean.GenParamBean;
import py.com.fms.fms.bean.MeasureUnitBean;
import py.com.fms.fms.bean.RefDetBean;
import py.com.fms.fms.bean.SupplierBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.bean.VoucherBean;
import py.com.fms.ven.persistence.services.FeesToCustomersServices;
import py.com.fms.ven.persistence.services.SalesServices;
import py.com.fms.fms.persistence.services.CurrencyServices;
import py.com.fms.fms.persistence.services.EnterpriseServices;
import py.com.fms.fms.persistence.services.GenParamServices;
import py.com.fms.fms.persistence.services.IvaServices;
import py.com.fms.fms.persistence.services.MeasureUnitServices;
import py.com.fms.fms.persistence.services.QuotationServices;
import py.com.fms.fms.persistence.services.RefServices;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.fms.persistence.services.VoucherServices;
import py.com.fms.fms.session.maintenances.EditNumbers;
import py.com.fms.exception.CommonException;
import py.com.fms.session.ComAssistant;
import py.com.fms.session.ParamHolder;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.session.modalSelectHolder;
import py.com.fms.utilities.ConvertAssistant;
import py.com.fms.utilities.DateAssistant;
import py.com.fms.utilities.NullAssistant;

@SuppressWarnings("unused")
@Name("trnSale")
@Scope(ScopeType.SESSION)
public class TrnSale {

	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private boolean editMode;
	private String initVar;
	private Date today = null;

	// Task Attendees Attributes
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{paramHolder}")
	private ParamHolder param;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In("#{comAssist}")
	private ComAssistant comAssist;
	@In
	Credentials credentials;
	@In
	Identity identity;
	private UsersBean user;

	// Attribute used for saving and deleting
	private SalesHeadBean salesHead;
	private SalesDetBean salesDet;

	private EditNumbers numbers;

	// Grilla detalle
	private List<SalesDetBean> allSalesDet;

	// Services
	private EnterpriseServices enSrv;
	private SalesServices prSrv;
	private FeesToCustomersServices fcSrv;
	private IvaServices txSrv;
	private QuotationServices qtSrv;
	private CurrencyServices crSrv;
	private UsersServices usSrv;
	private VoucherServices vouSrv;

	// For Query of all Sales
	private SalesHeadBean saleQueryHead;
	private SalesDetBean saleQueryDet;
	private Collection<SalesHeadBean> allSalesQueryHead;
	private Collection<SalesDetBean> allSalesQueryDet;

	// For Orders Cancellation
	private SalesHeadBean saleCancelHead;
	private SalesDetBean saleCancelDet;
	private Collection<SalesHeadBean> allSalesCancelHead;
	private Collection<SalesDetBean> allSalesCancelDet;

	// For Orders Confirmation
	private SalesHeadBean saleConfHead;
	private SalesDetBean saleConfDet;
	private Collection<SalesHeadBean> allSalesConfHead;
	private Collection<SalesDetBean> allSalesConfDet;

	private FeesToCustomersBean feesToCustomersQuery;
	private Collection<FeesToCustomersBean> allFeesToCustomersQuery;

	// Necessary Attributes;
	private static Boolean canSave;
	private EnterpriseBean entName = null;
	private EnterpriseBean entCod;
	private Long entId;
	private String operationType = "CNOR";
	private Boolean validateEntireForm = true;
	
	// RichFaces dataScroller variables
	private modalSelectHolder selectHolder;
	private HtmlDatascroller scroller = new HtmlDatascroller();
	private Integer scrollerPage = new Integer(0);
	private Boolean selectedAll = false;

	
	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] [[[[[[[[[[-------------]]]]]]]]]]
	 * 
	 * @throws CommonException
	 * Operation Types (Tipo de Operacion)
	 * -- CNOR = COMPRA NORMAL
	 * -- CPED = COMPRA A TRAVES DE PEDIDO
	 * -- NCRE = NOTA DE CREDITO
	 * 
	 */

	// Used to initialize information from a variable
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			System.out.println("INITIALIZING DATA ------------------");
			this.loadUserData();
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
//			this.loadDataGrid();
			this.initQueryObjects();

		}
		this.setInitVar(null);
		System.out.println("OUT");

	}

	// public void loadParams() throws CommonException{
	// this.param.initData();
	// this.param.loadParams();
	// }

	private void loadUserData() throws CommonException {
		System.out.println("Iniciando usuario compra");
		if (user == null) {
			user = new UsersBean();
		}
		if (usSrv == null) {
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		System.out.println("Antes de credential");
		if (user != null && credentials != null) {
			System.out.println("Credenciales Encontradas: " + credentials + "User: " + user);
			this.getUser().setUserName(credentials.getUsername());
			System.out.println("User Name: " + this.getUser().getUserName());
			try {
				this.setUser(usSrv.getUserDataByName(this.getUser().getUserName().toUpperCase().trim()));
			} catch (Exception e) {
				System.out.println("ERROR: " + e.getMessage());
			}
			
			this.setUser(this.user);
			System.out.println("User: " + this.getUser());
			System.out.println("User ENT: " + this.getUser().getIdEnt());
			System.out.println("User BRANCH: " + this.getUser().getDefaultBranch());
		} else {
			System.out.println("Credenciales Nulas");
		}
		System.out.println("Despues de credentials");
	}

	public void initBeans() {
		System.out.println("Initializing Entities");
		if (salesHead == null) {
			salesHead = new SalesHeadBean();
			salesHead.setIdEnt(this.user.getIdEnt());
			salesHead.setIdBranch(this.user.getDefaultBranch());
			salesHead.setDiscount(new BigDecimal(0));
			salesHead.setCharge(new BigDecimal(0));
		}

		if (salesDet == null) {
			salesDet = new SalesDetBean();
		}
		if (entCod == null) {
			entCod = new EnterpriseBean();
		}

		if (entName == null) {
			entName = new EnterpriseBean();
		}
		
		if(selectHolder == null){
			selectHolder = new modalSelectHolder();
		}
		
		

	}

	public void initServices() throws CommonException {
		System.out.println("Initializing Services");
		if (vouSrv == null) {
			vouSrv = new VoucherServices(this.sqlMap.getConfig());
		}
		if (prSrv == null) {
			prSrv = new SalesServices(this.sqlMap.getConfig());
		}

		if (enSrv == null) {
			enSrv = new EnterpriseServices(this.sqlMap.getConfig());
		}

		if (txSrv == null) {
			txSrv = new IvaServices(this.sqlMap.getConfig());
		}

		if (qtSrv == null) {
			qtSrv = new QuotationServices(this.sqlMap.getConfig());
		}

		if (crSrv == null) {
			crSrv = new CurrencyServices(this.sqlMap.getConfig());
		}

		if (fcSrv == null) {
			fcSrv = new FeesToCustomersServices(this.sqlMap.getConfig());
		}

	}

	public void initAssistants() {
		System.out.println("Initializing Assistants");

		if (aid == null) {
			aid = new WithinHolder();
		}

		if (param == null) {
			param = new ParamHolder();
		}

		if (convert == null) {
			convert = new ConvertAssistant();
		}

		if (comAssist == null) {
			comAssist = new ComAssistant();
		}

		if (numbers == null) {
			numbers = new EditNumbers();
		}

		if (facesMessages == null) {
			this.facesMessages = new FacesMessages();
		}

	}

	public void initCollections() {
		System.out.println("Initializing Collections");

		if (allSalesDet == null) {
			allSalesDet = new ArrayList<SalesDetBean>();
		}

	}

	/**
	 * Initialize Query objects
	 */
	public void initQueryObjects() {

		if (saleQueryHead == null) {
			saleQueryHead = new SalesHeadBean();
		}

		if (saleQueryDet == null) {
			saleQueryDet = new SalesDetBean();
		}

		if (allSalesQueryHead == null) {
			allSalesQueryHead = new ArrayList<SalesHeadBean>();
		}

		if (allSalesQueryDet == null) {
			allSalesQueryDet = new ArrayList<SalesDetBean>();
		}

		if (saleCancelHead == null) {
			saleCancelHead = new SalesHeadBean();
		}

		if (saleCancelDet == null) {
			saleCancelDet = new SalesDetBean();
		}

		if (allSalesCancelHead == null) {
			allSalesCancelHead = new ArrayList<SalesHeadBean>();
		}

		if (allSalesCancelDet == null) {
			allSalesCancelDet = new ArrayList<SalesDetBean>();
		}

		if (saleConfHead == null) {
			saleConfHead = new SalesHeadBean();
		}

		if (saleConfDet == null) {
			saleConfDet = new SalesDetBean();
		}

		if (allSalesConfHead == null) {
			allSalesConfHead = new ArrayList<SalesHeadBean>();
		}

		if (allSalesConfDet == null) {
			allSalesConfDet = new ArrayList<SalesDetBean>();
		}

		if (feesToCustomersQuery == null) {
			feesToCustomersQuery = new FeesToCustomersBean();
		}

		if (allFeesToCustomersQuery == null) {
			allFeesToCustomersQuery = new ArrayList<FeesToCustomersBean>();
		}
		
//		if (feesToCustomersQueryData == null) {
//			feesToCustomersQueryData = new PaymentOrderHeadBean();
//		}
//
//		if (allFeesToCustomersQueryData == null) {
//			allFeesToCustomersQueryData = new ArrayList<PaymentOrderDetBean>();
//		}


	}

	public void cleanData() {
		System.out.println("Cleaning Sales Data");
		entCod = null;
		entName = null;
		user = null;

		enSrv = null;
		crSrv = null;
		qtSrv = null;
		txSrv = null;
		usSrv = null;
		prSrv = null;
		vouSrv = null;

		aid = null;
		param = null;
		convert = null;
		comAssist = null;

		salesHead = null;
		salesDet = null;
		allSalesDet = null;

		numbers = null;

	}
	
	public void cleanQuery(){
		
		// First we clean
		saleQueryHead = null;
		saleQueryDet = null;
		allSalesQueryHead = null;
		allSalesQueryDet = null;
		
		// The we initialize objects
		this.initQueryObjects();
		
	}

	// Used to load a grid using a collection
//	private void loadDataGrid() {
//		try {
//			this.setAll(bcSrv.getAllBuyCondition());
//			for (BuyConditionBean buyCondition : this.getAllBuyCondition()) {
//				System.out.println(buyCondition.getDescrip());
//			}
//		} catch (CommonException e) {
//			e.printStackTrace();
//		}
//	}

	// Used to cancel
	public void cancelData() throws CommonException {
		// this.facesMessages.clear();
		System.out.println("Canceling OPERATION ---------------------------");
		this.cleanData();
		this.setInitVar("S");
		this.initData();

	}
	
	public void selectAll(ActionEvent event) {
		System.out.println("SELECTING ALL CHECKBOXES");
		
		// get the current scroller page
		int page = Integer.valueOf(scrollerPage).intValue();
		if (page != 0) {
		    page = page - 1;
		}
		int start = page * 10;
		int stop = (page * 10) + 10;
		if (stop > this.getAllSalesDet().size()) {
		    stop = this.getAllSalesDet().size();
		}
		System.out.println("> page: " + page + "; start: " + start + "; stop: " + stop);
		System.out.println("Selected All: " + this.selectedAll);
		
		// check the boxes on the active page
		if(this.selectedAll == true){
			for (int i = start; i < stop; i++) {
				this.allSalesDet.get(i).setSelected(true);
			}
		}
		
		// uncheck the boxes on the active page
		if(this.selectedAll == false){
			for (int i = start; i < stop; i++) {
				this.allSalesDet.get(i).setSelected(false);
			}
		}
		
		
	}
	
	public void deleteSelected(){
		System.out.println("DELETING SELECTEDS");
		Iterator<SalesDetBean> it = this.allSalesDet.iterator();
		while(it.hasNext()){
			SalesDetBean next = it.next();
			if(next.getSelected().equals(true)){
				it.remove();
			}
		}
		if(this.selectedAll.equals(true)){
			this.setSelectedAll(false);
		}
		this.calcHeadAmounts();
		
	}

//	public Boolean activeSupplyDepend() {
//
//		if (this.getSalesDet().getSupplyData() == null) {
//			System.out.println("RENDER TAX: TRUE");
//			return true;
//		} else {
//			System.out.println("RENDER TAX: FALSE");
//			return false;
//		}
//	}

	/**
	 * Habilita la lista de pedidos confirmados para un determinado proveedor
	 */
//	public Boolean activeOrderQuery() {
//		if (this.getSalesHead().getSupplierData() == null) {
//			System.out.println("* activeOrderQuery RENDER ORDER QUERY: FALSE");
//			return false;
//
//		} else {
//			if (aid.supplierOrdersList(this.getSalesHead().getSupplierData().getId()).isEmpty()) {
//				System.out.println("** activeOrderQuery RENDER ORDER QUERY: FALSE");
//				return false;
//			} else {
//				System.out.println("*** activeOrderQueryRENDER ORDER QUERY: TRUE");
//				return true;
//			}
//		}
//
//	}

	
	public void retrieveSupplyData() throws CommonException {
		System.out.println("RETRIEVING SUPPLY DATA");
		if (this.getSalesDet().getSupplyData() == null) {
			System.out.println("POR FAVOR ELIJA EL INSUMO");
		} else {
			Long taxId = new Long(0);
			taxId = this.getSalesDet().getSupplyData().getTax();
			this.getSalesDet().setTaxData(this.txSrv.getTaxData(taxId));
			if(this.getSalesDet().getMeasureUnitData() != null){
//				this.retrieveSupplyCost();
			}
			System.out.println("TAX DATA: ".concat(this.getSalesDet().getTaxData().getId().toString()));
		}

	}

	public void retrieveChangeType() throws ParseException, CommonException {
		System.out.println("RETRIEVING CHANGE TYPE");
		// First we verify for null object
		if (this.getSalesHead().getCurrencyData() == null) {
			System.out.println("Currency Data is NULL");
		} else {
			// If object is not null
			// We retrieve the parameters
			Long localCurrency = this.crSrv.getIdCurrency("GUAR");
			Long idCurrency = this.getSalesHead().getCurrencyData().getId();
			if (idCurrency.equals(localCurrency)) {
				this.getSalesHead().setChangeType(new Double(1));
			} else {
				Date startDate = DateAssistant.getCurrentDate();
				System.out.println(" ##### CHANGE TYPE DATE: ".concat(startDate.toString()).concat(" ##### "));
				System.out.println(" ##### currency id = ".concat(idCurrency.toString()).concat(" ##### "));
				// Then we retrieve the changeType based on passed parameters
				Double changeType = (Double) this.qtSrv.getAmountQuotation(idCurrency, startDate);

				// And set the changeType value
				if (changeType == null) {
					FacesMessages.instance().add("La moneda seleccionada no tiene cotizaci�n para la fecha actual. Favor inserte cotizaci�n para la fecha.");
					this.getSalesHead().setChangeType(new Double(0));
				} else {
					this.getSalesHead().setChangeType(changeType);
					System.out.println("CHANGE TYPE: " + (this.getSalesHead().getChangeType()));
				}
			}
		}
	}
	
//	public void retrieveSupplyCost(){
//		if(this.getSalesDet().getSupplyData() == null || this.getSalesDet().getMeasureUnitData() == null){
//			System.out.println("COST STOCK DATA Data is NULL");
//		}else{
//			try {
//			// OOOOOOOOOOOJOOOOOOOOOOOOOOO SUCURSAL TRAER DEL FORMULARIOOOOOOOOOOOOOOOOOOOOOOOO
//			Long supply = this.getSalesDet().getSupplyData().getId();
//			Long branch = new Long(this.user.getDefaultBranch());
//			Long measureUnit = this.getSalesDet().getMeasureUnitData().getId();
//			// Retrieve Supply Cost Stock Data
//			SupplyCostStockBean costStockData;
//			costStockData = scstSrv.getSupplyCostStockData(supply, branch, measureUnit);
//			if(costStockData != null){
//				this.getSalesDet().setGrossCost(costStockData.getGrossCost());
//			}else{
//				this.getSalesDet().setGrossCost(null);
//			}
//			} catch (CommonException e) {
//				// TODO Auto-generated catch block
//				System.out.println(e.getMessage());
//				e.printStackTrace();
//			}
//		}
//	}
	
	public void selectCustomer(CustomerBean customer){
		System.out.println("Selecting Customer");
		this.getSalesHead().setCustomerData(null);
		if(customer.getCod() == null){
			comAssist.generateErrorMsg("Favor seleccione un proveedor", "actionForm:acceptSelectedCustomer");
		}else{
			System.out.println("Selecting Customer: "+customer.getCod());
			this.getSalesHead().setCustomerData(customer);
		}	
	}

	/**
	 * Rellena los campos del formulario de compras si se ha seleccionado un
	 * pedido
	 */
//	public void fillFromOrder() {
//		try {
//			if (this.getSalesHead().getOrderHeadData() != null) {
//
//				// Cleaning Data
//				this.getAllOrderDet().clear();
//				this.getAllSalesDet().clear();
//
//				// Filling the header
//				this.getSalesHead().setBuyConditionData(convert.getBuyConditionData(this.getSalesHead().getOrderHeadData().getBuyCondition()));
//				this.getSalesHead().setBuyTypeData(convert.getRefDetData(this.getSalesHead().getOrderHeadData().getBuyType()));
//				this.getSalesHead().setCurrencyData(convert.getCurrencyData(this.getSalesHead().getOrderHeadData().getCurrency()));
//				this.getSalesHead().setChangeType(this.getSalesHead().getOrderHeadData().getChangeType());
//				this.getSalesHead().setCostCenterData(convert.getRefDetData(this.getSalesHead().getOrderHeadData().getCostCenter()));
//				this.getSalesHead().setDiscount(this.getSalesHead().getOrderHeadData().getDiscount());
//
//				// Filling details
//
//				this.setAllOrderDet(orSrv.getOrderDetByHeadId(this
//						.getSalesHead().getOrderHeadData().getId()));
//				System.out.println("FILL FROM ORDER - ALL ORDERS: "
//						+ this.getAllOrderDet());
//
//				Iterator<OrderDetBean> it = this.allOrderDet.iterator();
//				while (it.hasNext()) {
//					OrderDetBean next = it.next();
//					System.out.println("FILL FROM ORDER - NEXT: " + next);
//					this.getSalesDet().setSupplyData(convert.getSupplyData(next.getSupply()));
//					this.getSalesDet().setMeasureUnitData(convert.getMeasureUnitData(next.getMeasureUnit()));
//					this.getSalesDet().setGrossCost(next.getGrossCost());
//					this.getSalesDet().setOrderQuantity(next.getQuantity() - next.getInvoiceQuantities());
//					this.getSalesDet().setQuantity(next.getQuantity() - next.getInvoiceQuantities());
//					this.getSalesDet().setTaxData(convert.getTaxData(next.getTax()));
//					this.getSalesDet().setDiscount(next.getDiscount());
//					this.getSalesDet().setCharge(next.getCharge());
//
//					this.insertDetail();
//					if (this.salesDet == null) {
//						this.salesDet = new SalesDetBean();
//					}
//				}
//				
//				// Setting Operation Type
//				this.setOperationType("CPED");
//
//			}else{
//				// Clean Objects
//				this.getSalesHead().setBuyConditionData(null);
//				this.getSalesHead().setBuyTypeData(null);
//				this.getSalesHead().setCurrencyData(null);
//				this.getSalesHead().setChangeType(null);
//				this.getSalesHead().setCostCenterData(null);
//				this.getSalesHead().setDiscount(null);
//				this.getAllOrderDet().clear();
//				this.getAllSalesDet().clear();
//				// Setting Operation Type
//				this.setOperationType("CNOR");
//				
//			}
//		} catch (CommonException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}

	// This method process the detail data and insert into a collection
	public void insertDetail() {
//		try {
//			Boolean canInsert = true;
//			// First we validate the form
//			if (this.getSalesHead().getOrderHeadData() == null){
//				this.comAssist.validateSalesDet(this.getSalesDet());
//			}
//			System.out.println("Inserting Detail");
//			System.out.println("SUPPLY: ".concat(this.getSalesDet().getSupplyData().getCod().toString()));
//			System.out.println("Bean: ".concat(this.getSalesDet().toString()));
//			// We Verify if the item exist in the list
//			if(this.allSalesDet.size() > 0){
//				System.out.println("NOT EMPTY LIST: " + this.allSalesDet.size());
//				for(SalesDetBean detBean : this.allSalesDet){
//					if(this.getSalesDet().getSupplyData().getId().equals(detBean.getSupplyData().getId()) 
//						&& this.getSalesDet().getMeasureUnitData().getId().equals(detBean.getMeasureUnitData().getId())){
//						System.out.println("EQUAL: "+ 
//								this.getSalesDet().getSupplyData().getId() + " == "+ detBean.getSupplyData().getId() + " - " +
//								this.getSalesDet().getMeasureUnitData().getId() + " == "+ detBean.getMeasureUnitData().getId());
//						this.comAssist.generateErrorMsg(
//								"El insumo seleccionado ya existe en la grilla",
//								"actionform:insDetailBtn");
//						canInsert = false;
//						break;
//					}
//				}
//				if(canInsert == true){
//					this.processDetForInsert();
//				}
//			}else{
//				System.out.println("EMPTY LIST: ");
//				this.processDetForInsert();
//			}
//
//			
//			
//			
//
//		} catch (Exception e) {
//			// this.facesMessages.add(Severity.ERROR, e.getMessage());
//			log.error(e);
//		}
	}
		
	public void processDetForInsert(){
//		try{
//			if (this.getSalesDet() == null) {
//				System.out.println("Detail Bean is NULL");
//			} else {
//				// First we calculate the Net Cost
//				if(this.getSalesDet().getDiscount() == null){
//					this.getSalesDet().setDiscount(new BigDecimal(0));
//				}
//				if(this.getSalesDet().getCharge() == null){
//					this.getSalesDet().setCharge(new BigDecimal(0));
//				}
//				System.out.println("GROSS COST: " + (this.getSalesDet().getGrossCost()));
//				System.out.println("DISCOUNT: " + (this.getSalesDet().getDiscount()));
//				System.out.println("CHARGE: " + (this.getSalesDet().getCharge()));
//				
//				// Then we calculate the net cost
//				Double netCost = (this.getSalesDet().getGrossCost().doubleValue())
//							   - (this.getSalesDet().getDiscount().doubleValue()) 
//							   + (this.getSalesDet().getCharge().doubleValue());
//				Double netCostRounded = ComAssistant.round(netCost, 5);
//				this.getSalesDet().setNetCost(new BigDecimal(Double.toString(netCostRounded)));
//				
//				// Then we calculate the item total based in calculated net cost
//				Double itemTotal = (this.getSalesDet().getQuantity().doubleValue()) * (this.getSalesDet().getNetCost().doubleValue());
//				Double itemTotalRounded = ComAssistant.round(itemTotal, 5);
//				this.getSalesDet().setItemAmount(new BigDecimal(Double.toString(itemTotal)));
//
//				// Processing Tax
//				this.comAssist.processTax(this.getSalesDet().getTaxData(),this.getSalesDet().getItemAmount());
//
//				// Setting tax fields
//				this.getSalesDet().setTaxedAmount(this.comAssist.getTaxedTotal());
//				this.getSalesDet().setExemptAmount(this.comAssist.getExemptTotal());
//				this.getSalesDet().setTaxAmount(this.comAssist.getTaxTotal());
//
//				// Calculating basic quantity
//				Double basicQuantities = (this.getSalesDet().getMeasureUnitData().getQuantity()) * (this.getSalesDet().getQuantity());
//				this.getSalesDet().setBasicQuantities(basicQuantities);
//				System.out.println("AFTER TAXING OPERATION - ".concat(this.getSalesDet().getItemAmount().toString()));
//				
//				// Add the Object into a collection
//				if (this.getSalesDet().getItemAmount().longValue() <= 0) {
//					System.out.println("TOTAL INVALIDO");
//				} else {
//					this.allSalesDet.add(this.getSalesDet());
//					System.out.println("Collection allSalesDet =".concat(this.allSalesDet.toString()));
//					this.calcHeadAmounts();
//					this.setSalesDet(null);
//					this.setInitVar("S");
//				}
//
//			}
//			
//		}catch (Exception e) {
//			// this.facesMessages.add(Severity.ERROR, e.getMessage());
//			log.error(e);
//		}
	}

	public void calcHeadAmounts() {

		// Initializing Variables
		Double totalAmount = new Double(0);
		Double totalExempt = new Double(0);
		Double totalTax = new Double(0);

		if(allSalesDet.isEmpty()){
			this.getSalesHead().setTotal(null);
			this.getSalesHead().setExemptTotal(null);
			this.getSalesHead().setTaxTotal(null);
		}else{
			// Defining an Iterator
			Iterator<SalesDetBean> it1 = allSalesDet.iterator();

			// Walking trough collection
			while (it1.hasNext()) {
				// Setting the next reg
				SalesDetBean nextDet = it1.next();
				System.out.println("Next:".concat(nextDet.toString()));
				// Calculating the addition
				totalAmount += nextDet.getItemAmount().doubleValue();
				totalExempt += nextDet.getExemptAmount().doubleValue();
				totalTax += nextDet.getTaxAmount().doubleValue();
				
			}

			System.out.println("Total amount:".concat(totalAmount.toString()));
			if (totalAmount == null || totalAmount <= 0) {
				System.out.println("Invalid Total:".concat(totalAmount.toString()));
			} else {
				// If addition is not null set the head total
				Double roundedTotalAmount = ComAssistant.round(totalAmount, 5);
				this.getSalesHead().setTotal(new BigDecimal(Double.toString(roundedTotalAmount)));
				
			}
			if (totalTax == null || totalTax <= 0) {
				System.out.println("Invalid TotalTax:".concat(totalTax.toString()));
			} else {
				// If addition is not null set the head total
				Double roundedTotalTax = ComAssistant.round(totalTax, 5);
				this.getSalesHead().setTaxTotal(new BigDecimal(Double.toString(roundedTotalTax)));
				
			}
			if (totalExempt == null || totalExempt <= 0) {
				System.out.println("Invalid totalExcempt:".concat(totalExempt.toString()));
			} else {
				// If addition is not null set the head total
				Double roundedTotalExempt = ComAssistant.round(totalExempt, 5);
				this.getSalesHead().setExemptTotal(new BigDecimal(Double.toString(roundedTotalExempt)));
				
			}
		}
		
	}

	// Used for data saving process
	public void saveNewData() throws ParseException, SQLException {
//		// save new data by Bruno - Canapech.
//		System.out.println("OPERATION: " + this.getOperationType());
//		this.setValidateEntireForm(true);
//		Boolean validForm = comAssist.validateSalesForm(this.salesHead,
//				this.allSalesDet);
//		if (validForm == true) {
//			try {
//				
//				SalesHeadBean newSalesHead = new SalesHeadBean();
//				SalesDetBean newSalesDet = new SalesDetBean();
//				// RETRIEVING ENTERPRISE AND BRANCH ID
//				/*OOOOOOOOOJOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
//				 *OOOOOOOOOJOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
//				 *EMPRESA Y SUCURSAL SE DEBEN TRAER DEL VALOR DEL FORMULARIO 
//				 *NO DIRECTAMENTE DEL USUARIO
//				 *CAMBIAR LUEGOOOOOOOOOOOOOOOOOOO
//				 * */
//				newSalesHead.setIdEnt(this.user.getIdEnt());
//				newSalesHead.setIdBranch(this.user.getDefaultBranch());
//				
//				if(this.getOperationType().equals("CPED")){
//					this.setOrderHead(this.getSalesHead().getOrderHeadData());
//				}
//
//				// INITIALIZING OBJECTS IN THE NUMBER GENERATION CLASS
//				this.numbers.setInitVar("S");
//				this.numbers.initData();
//
//				// SETTING FIELDS
//				// Invoice Number Fields
//				newSalesHead.setEstablishment(NullAssistant.checkNullString(this.getSalesHead().getEstablishment()));
//				newSalesHead.setExpedition(NullAssistant.checkNullString(this.getSalesHead().getExpedition()));
//				newSalesHead.setStamping(NullAssistant.checkNullString(this.getSalesHead().getStamping()));
//				newSalesHead.setVoucher(NullAssistant.checkNullString(this.getSalesHead().getVoucher()));
//
//				// Other Fields
//				newSalesHead.setBuyCondition(NullAssistant.checkNullLong(this.getSalesHead().getBuyConditionData().getId()));
//				newSalesHead.setBuyType(NullAssistant.checkNullLong(this.getSalesHead().getBuyTypeData().getId()));
//				newSalesHead.setChangeType(NullAssistant.checkNullDouble(this.getSalesHead().getChangeType()));
//				newSalesHead.setCostCenter(NullAssistant.checkNullLong(this.getSalesHead().getCostCenterData().getId()));
//				newSalesHead.setCurrency(NullAssistant.checkNullLong(this.getSalesHead().getCurrencyData().getId()));
//				newSalesHead.setTaxTotal(NullAssistant.checkNullBigDecimal(this.getSalesHead().getTaxTotal()));
//				newSalesHead.setExemptTotal(NullAssistant.checkNullBigDecimal(this.getSalesHead().getExemptTotal()));
//				newSalesHead.setGravTotal(NullAssistant.checkNullBigDecimal(this.getSalesHead().getGravTotal()));
//				newSalesHead.setDiscount(NullAssistant.checkNullBigDecimal(this.getSalesHead().getDiscount()));
//				newSalesHead.setCharge(NullAssistant.checkNullBigDecimal(this.getSalesHead().getCharge()));
//				newSalesHead.setIdSupplier(NullAssistant.checkNullLong(this.getSalesHead().getSupplierData().getId()));
//				newSalesHead.setTotal(NullAssistant.checkNullBigDecimal(this.getSalesHead().getTotal()));
//				newSalesHead.setIdTypeTrans(NullAssistant.checkNullLong(this.getSalesHead().getVoucherData().getId()));
//				newSalesHead.setIdTypeTransRef(NullAssistant.checkNullLong(this.getSalesHead().getIdTypeTransRef()));
//
//				// Date Fields
//				newSalesHead.setVoucherDate(this.getSalesHead().getVoucherDate()); // date of the provider invoice
//				newSalesHead.setStartDate(DateAssistant.getHoleDateTime()); // date when invoice was generated
//				newSalesHead.setStatusDate(DateAssistant.getHoleDateTime()); // date
//				newSalesHead.setStatus("PEND");
//
//				prSrv.saveNewSalesHead(newSalesHead);
//
//				System.out.println("THIS.ORDERHEAD.GETBUYCONDITIONDATA() = ".concat(this.getSalesHead().getBuyConditionData().getId().toString()));
//				System.out.println("this.orderHead.getCostCenterData() = ".concat(this.getSalesHead().getCostCenterData().getId().toString()));
//				System.out.println("this.orderHead.getCurrencyData() = ".concat(this.getSalesHead().getCurrencyData().getId().toString()));
//				System.out.println("this.orderHead.getChangeType() = "+ this.getSalesHead().getChangeType());
//
//				// Retrieving Header Id
//				Long idHead = new Long(0);
//				idHead = prSrv.getSalesHeadIdByEntSalesUk(
//						newSalesHead.getIdEnt(), 
//						newSalesHead.getIdTypeTrans(), 
//						newSalesHead.getEstablishment(),
//						newSalesHead.getExpedition(),
//						newSalesHead.getVoucher(),
//						newSalesHead.getIdSupplier());
//
//				System.out.println("HEAD = " + idHead);
//
//				// SAVING DETAIL
//				Integer vContador = new Integer(0);
//				for (SalesDetBean bean : allSalesDet) {
//					vContador++;
//
//					// Processing Tax
//					// this.comAssist.processTax(this.getSalesDet().getTaxData(),
//					// this.getSalesDet().getItemTotal());
//					System.out.println("###### vContador  #####".concat(vContador.toString()));
//
//					// Setting Fields
//					newSalesDet.setIdHead(idHead);
//					newSalesDet.setItem(new Long(vContador));
//					newSalesDet.setSupply(bean.getSupplyData().getId());
//					newSalesDet.setMeasureUnit(bean.getMeasureUnitData().getId());
//					newSalesDet.setBasicQuantities(bean.getBasicQuantities());
//					newSalesDet.setOldGrossCost(new BigDecimal(0));
//					newSalesDet.setGrossCost(bean.getGrossCost());
//					newSalesDet.setQuantity(bean.getQuantity());
//					newSalesDet.setTax(bean.getTaxData().getId());
//					newSalesDet.setDiscount(bean.getDiscount());
//					newSalesDet.setCharge(bean.getCharge());
//					newSalesDet.setNetCost(bean.getNetCost());
//					newSalesDet.setItemAmount(bean.getItemAmount());
//					newSalesDet.setTaxAmount(bean.getTaxAmount());
//					newSalesDet.setTaxedAmount(bean.getTaxedAmount());
//					newSalesDet.setExemptAmount(bean.getExemptAmount());
//
//					prSrv.saveNewSalesDet(newSalesDet);
//					
//					if(this.getOperationType().equals("CPED")){
//						if(bean.getQuantity().equals(bean.getOrderQuantity())){
//							this.getOrderHead().setStatus("FACT");
//						}
//						orSrv.updateInvoiceQuantities(this.getOrderHead().getId(), new Long(vContador), bean.getQuantity(), this.getOrderHead().getStatus());
//					}	
//				}
//				this.comAssist.generateInfoMsg(
//						"Compra Registrada de forma Exitosa",
//						"actionform:saveRegBtn");
//				this.setValidateEntireForm(false);
//				this.cleanData(); // Cleaning Objects
//				this.setInitVar("S"); // Setting initialization Flag
//
//			} catch (CommonException e) {
//				// TODO: handle exception
//				// this.facesMessages.add(Severity.ERROR, e.getMessage());
//				System.out.println("NO SE PUDO INSERTAR. ".concat(e
//						.getMessage().toString()));
//
//				log.error(e);
//			}
//		}
//
	}

	/**
	 * Sales Query.
	 * 
	 * @throws SQLException
	 * @throws SQLException
	 */

	public void retrieveFilteredSales() throws SQLException {
		try {
			Long idSupplier = null;
			String status = null;
			Date voucherDate = null;

			if (this.getSaleQueryHead().getCustomerData() != null) {
				idSupplier = this.getSaleQueryHead().getCustomerData()
						.getId();
			}
			if (this.getSaleQueryHead().getStatus() != null) {
				status = this.getSaleQueryHead().getStatus();
			}

			if (this.getSaleQueryHead().getVoucherDate() != null) {
				voucherDate = this.getSaleQueryHead().getVoucherDate();
				System.out.println("VOUCHER DATE. " + this.getSaleQueryHead().getVoucherDate());
			}

			this.setAllSalesQueryHead(prSrv.getFilteredSales(idSupplier,status, voucherDate));
			
			if(this.allSalesQueryHead.isEmpty()){
				this.comAssist.generateInfoMsg("No se encontraron Facturas", "actionform:pQuerySearchBtn");
			}
			
		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}

	}

	public void retrievePendingSales(SalesHeadBean saleHeadp,
			String operation) throws SQLException {
		try {
			Long idSupplier = null;
			Date voucherDate = null;
			String status = new String("PEND");
			if (saleHeadp.getCustomerData() != null) {
				idSupplier = saleHeadp.getCustomerData().getId();
			}

			if (saleHeadp.getVoucherDate() != null) {
				voucherDate = saleHeadp.getVoucherDate();
			}
			if (operation.equals("CONFIRM")) {
				this.setAllSalesConfHead(prSrv.getPendingSales(
						idSupplier, voucherDate, status));
				System.out.println("PENDING PURCHASES LIST CONFIRM: "
						+ this.allSalesConfHead);
				if(this.allSalesConfHead.isEmpty()){
					this.comAssist.generateInfoMsg("No Existen Facturas con estado Pendiente", "actionform:pConfSearchBtn");
				}
			}

			if (operation.equals("CANCEL")) {
				this.setAllSalesCancelHead(prSrv.getPendingSales(
						idSupplier, voucherDate, status));
				System.out.println("PENDING PURCHASES LIST CANCEL: "
						+ this.allSalesCancelHead);
				if(this.allSalesCancelHead.isEmpty()){
					this.comAssist.generateInfoMsg("No Existen Facturas con estado Pendiente", "actionform:pCancelSearchBtn");
				}
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}

	}

	public void retriveSalesDet(Long idHead, String operation) {

		try {
			if (operation.equals("QUERY")) {
				this.setAllSalesQueryDet(prSrv
						.getSalesDetByHeadId(idHead));
				System.out.println("QUERY PURCHASE DET: "
						+ this.allSalesQueryDet);
			}
			if (operation.equals("CONFIRM")) {
				this
						.setAllSalesConfDet(prSrv
								.getSalesDetByHeadId(idHead));
				System.out.println("CONFIRM PURCHASE DET: "
						+ this.allSalesConfDet);
			}
			if (operation.equals("CANCEL")) {
				this.setAllSalesCancelDet(prSrv
						.getSalesDetByHeadId(idHead));
				System.out.println("CANCEL PURCHASE DET: "
						+ this.allSalesCancelDet);
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}
	}

//	public void retrieveFeesToCustomersBySupplierId() {
//		try {
//			Long idSupplier = null;
//			if (this.getFeesToCustomersQueryData().getSupplierData() == null) {
//				this.comAssist.generateErrorMsg("Seleccione un proveedor",
//						"actionform:searchBtn");
//			} else {
//				idSupplier = this.getFeesToCustomersQueryData().getSupplierData().getId();
//				this.setAllFeesToCustomersQueryData(fcSrv
//						.getFeesToCustomersQuery(
//								this.user.getIdEnt(), 
//								idSupplier));
//				System.out.println("FEES TO SUPPLIERS: "
//						+ this.getAllFeesToCustomersQueryData().size());
//			}
//			Iterator<PaymentOrderDetBean> it = allFeesToCustomersQueryData.iterator();
//			while(it.hasNext()){
//				PaymentOrderDetBean next = it.next();
//				System.out.println("FEC-FACTURA: "+ next.getVoucherDate());
//				System.out.println("NRO-FACTURA: "+ this.comAssist.getInvoiceNumber(
//						next.getEstablishment(), 
//						next.getExpedition(), 
//						next.getVoucher(), 
//						next.getInstalments()));
//				System.out.println("SALDO: "+ next.getResiduePaymentOrden());
//			}
//
//		} catch (CommonException e) {
//			// TODO: handle exception
//			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());
//
//			log.error(e);
//		}
//	}

	public void confirmSales() throws SQLException {
		try {
			Boolean noneSelected = true;
			Iterator<SalesHeadBean> it = allSalesConfHead.iterator();

			while (it.hasNext()) {
				SalesHeadBean salesHeadBean = it.next();
				if (salesHeadBean.getSelected() == true) {
					noneSelected = false;
					System.out.println("antes de confirmar la factura "
							+ salesHeadBean.getEstablishment() + "-"
							+ salesHeadBean.getExpedition() + "-"
							+ salesHeadBean.getVoucher());
					this.prSrv.confirmSale(salesHeadBean.getId());
					System.out
							.println("despues de confirmar, se commiteo, esta mal peor luego lo vemos :) ");
					/* Actualizar stock y costos */
					System.out
							.println("**** antes de suppliesCostStockProcess ****");
					suppliesCostStockProcess(salesHeadBean);
					/* generar cuotas a proveedor */
					System.out
							.println("**** antes de feesToCustomersProcess ****");
//					feesToCustomersProcess(salesHeadBean);
					System.out
							.println("**** despues de feesToCustomersProcess ****");
				}
				if(!it.hasNext()){
					this.comAssist.generateInfoMsg(
							"Comfirmaci�n realizada con �xito!",
							"actionform:saleConfBtn");
				}
			}

			if (noneSelected == true) {
				this.comAssist.generateErrorMsg(
						"Favor seleccione al menos un registro",
						"actionform:saleConfBtn");
			} else {
				this.retrievePendingSales(this.getSaleConfHead(),
						"CONFIRM");
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());
			log.error(e);
		}

	}

	private void suppliesCostStockProcess(SalesHeadBean salesHeadBean) {
		long operacionStock = 0;
		BigDecimal vAvgCost = new BigDecimal(0);
		VoucherBean vouBean = new VoucherBean();
		System.out.println("antes de ir a consultar voucher "
				+ salesHeadBean.getSaleType());

		try {
			vouBean = vouSrv.getVoucherData(salesHeadBean.getIdTypeTrans());
			if (vouBean == null) {
				System.out.println("vouBean == null");
				this.comAssist.generateErrorMsg(
						"No existe tipo de comprobante seleccionado",
						"actionform:confirmBtn");
			} else {
				System.out.println("***** vouBean no es nulo : ) *****");
				if (vouBean.getOperateStock().equals("S")) {
					System.out.println("=S=1");
					operacionStock = 1;
				}
				if (vouBean.getOperateStock().equals("R")) {
					System.out.println("=R=-1");
					operacionStock = -1;
				}
				if (vouBean.getOperateStock().equals("N")) {
					System.out.println("=N=0");
					operacionStock = 0;
				}
			}
		} catch (CommonException e) {
			System.out.println("No se ha encontrado getVoucherData ** "
					.concat(e.getMessage().toString()));
			log.error(e);
		}

		/**
		 * Buscamos el valor parametrizado de cantidad quiebre stock por defecto
		 * en parametros generales
		 */
		System.out.println("** buscamos el parametro STOCK_MIN_DEFAULT **");
		GenParamBean genParBean = new GenParamBean();
		GenParamServices genParSrv;
		try {
			genParSrv = new GenParamServices(this.sqlMap.getConfig());
			genParBean = genParSrv.getGenParamBeanByEntAndCod(salesHeadBean
					.getIdEnt(), "STOCK_MIN_DEFAULT");
		} catch (CommonException e) {
			System.out
					.println("No se ha encontrado parametros generales STOCK_MIN_DEFAULT ** "
							.concat(e.getMessage().toString()));
			log.error(e);
		}

		if (genParBean == null) {
			/*
			 * Si no existe seteado el registro le agregamos a 15.
			 */
			System.out.println("** STOCK_MIN_DEFAULT==null, 15 default **");
			genParBean.setParamValues("15");
		}

		/**
		 * buscamos la cantidad de la unidad de medida
		 */
		try {
			System.out.println("** unidad de medida **");
			MeasureUnitBean measureUnitBean = new MeasureUnitBean();
			MeasureUnitServices muSrv = new MeasureUnitServices(this.sqlMap
					.getConfig());

			/**
    		 * 
    		 */

			/**
			 * bean y services para insertar o actualizar el stock y los costos
			 */
			System.out.println("** suplyCostStkBean :) **");
//			SupplyCostStockBean suplyCostStkBean = new SupplyCostStockBean();
//			SupplyCostStockServices supSrv = new SupplyCostStockServices(
//					this.sqlMap.getConfig());

			/**
			 * Creamos una coleccion para buscar el detalle de la comprara e ir
			 * insertando en la tabla de costos y stock a partir de la lista
			 * generada en la factura de compra...
			 */
			System.out.println("** salesDetList :) **");
			Collection<SalesDetBean> salesDetList = null;
			SalesDetBean purcDetBean = new SalesDetBean();
			SalesServices purSrv = new SalesServices(this.sqlMap
					.getConfig());
			/**
			 * obtenemos el detalle a partir del id de la cabecera de la factura
			 */
			salesDetList = purSrv.getSalesDetByHeadId(salesHeadBean
					.getId());
			Iterator<SalesDetBean> it = salesDetList.iterator();
			System.out.println("** antes del iterator de  salesDetList**");
			while (it.hasNext()) {
				SalesDetBean salesDetBean = it.next();
				/**
				 * Unique en la tabla de stock y costo son el articulo, la
				 * sucursal y la unidad de medida
				 */
				System.out
						.println("** entramos al while para buscar el registro de getSupplyCostStockData **");
//				suplyCostStkBean = supSrv.getSupplyCostStockData(
//						salesDetBean.getSupply(), salesHeadBean
//								.getIdBranch(), salesDetBean
//								.getMeasureUnit());
//				measureUnitBean = muSrv.getMeasureUnitData(salesDetBean
//						.getMeasureUnit());
//				if (suplyCostStkBean == null) {
//					SupplyCostStockBean suplyCostStkBeanIns = new SupplyCostStockBean();
//					SupplyCostStockServices supSrvIns = new SupplyCostStockServices(
//							this.sqlMap.getConfig());
					/**
					 * insertar un registro en costo sucursal para el insumo, la
					 * sucursal y la unidad de medida
					 */
//					System.out
//							.println("***# no existe el registro en suplyCostStkBean, lo creamos salesDetBean.getSupply()= ***"
//									+ salesDetBean.getSupply());
//					// suplyCostStkBean.setSupply(salesDetBean.getSupply());
//					suplyCostStkBeanIns.setSupply(salesDetBean.getSupply());
//					System.out.println("*** 1");
//					System.out.println("salesDetBean.getSupply()= "
//							+ salesDetBean.getSupply());
//					suplyCostStkBeanIns.setIdBranch(salesHeadBean
//							.getIdBranch());
//					System.out.println("*** 2");
//					suplyCostStkBeanIns.setIdMeasureUnit(salesDetBean
//							.getMeasureUnit());
//					System.out.println("*** 3");
//					suplyCostStkBeanIns
//							.setStock(salesDetBean.getQuantity());
					/**
					 * por defecto enviamos el campo de cantidad para la
					 * cantidad física Una vez realizado el inventario esto debe
					 * de ser actualizado con el valor del inventario para este
					 * articulo, unidad de medida y sucursal
					 */
//					System.out.println("*** 4");
//					suplyCostStkBeanIns.setRealStock(salesDetBean
//							.getQuantity()
//							* operacionStock);
//					System.out.println("*** 5");
//					suplyCostStkBeanIns.setMinStock(new Double(genParBean
//							.getParamValues()));
//					System.out.println("*** 6");
//					suplyCostStkBeanIns.setBasicStock(salesDetBean
//							.getQuantity()
//							* measureUnitBean.getQuantity() * operacionStock);
//					System.out.println("*** 7");
//					suplyCostStkBeanIns.setIdCurrency(salesHeadBean
//							.getCurrency());
//					System.out.println("*** 8");
//					suplyCostStkBeanIns.setNetCost(salesDetBean
//							.getNetCost());
//					System.out.println("*** 9");
//					suplyCostStkBeanIns.setGrossCost(salesDetBean
//							.getGrossCost());
					/**
					 * --------------------------------------------------------
					 * --- -- CALCULO DE COSTO PROMEDIO. --
					 * ----------------------
					 * ------------------------------------- -- REFERENCIAS: --
					 * --
					 * ---------------------------------------------------------
					 * -- CM = Cantidad del Movimiento. -- -- CT = Costo de
					 * Transferencia. -- -- CP = Costo Promedio Actual. -- -- EX
					 * = Existencia Actual. --
					 * ----------------------------------
					 * ------------------------- -- FORMULA: ( ( CM * CT ) + (
					 * CP * EX ) ) / ( EX + CM ); --
					 * ----------------------------
					 * -------------------------------
					 */
					System.out.println("*** 10");
					vAvgCost = new BigDecimal(salesDetBean.getQuantity() * measureUnitBean.getQuantity());
					System.out.println("*** 11");
					vAvgCost = new BigDecimal(vAvgCost.doubleValue()* salesDetBean.getNetCost().doubleValue());
					System.out.println("*** 12");
					vAvgCost = new BigDecimal(vAvgCost.doubleValue() + (0 * 0));
					System.out.println("*** 13");
					vAvgCost = new BigDecimal(vAvgCost.doubleValue() / (0 + (salesDetBean.getQuantity() * measureUnitBean.getQuantity())));
					System.out.println("*** 14");
//					suplyCostStkBeanIns.setAverageCost(vAvgCost);
//					System.out.println("*** 15");
//					supSrvIns.saveNewSupplyCostStock(suplyCostStkBeanIns);
//					System.out.println("*** 16");
//				} else {
//					/*
//					 * alterar los valores para insertar el stock y los costos
//					 * nuevos
//					 */
//					suplyCostStkBean.setStock(suplyCostStkBean.getStock() + (salesDetBean.getQuantity() * operacionStock));
//					suplyCostStkBean.setBasicStock(suplyCostStkBean.getBasicStock()+ (salesDetBean.getQuantity()* measureUnitBean.getQuantity() * operacionStock));
//
//					suplyCostStkBean.setNetCost(salesDetBean.getNetCost());
//					suplyCostStkBean.setGrossCost(salesDetBean.getGrossCost());
					/**
					 * --------------------------------------------------------
					 * --- -- CALCULO DE COSTO PROMEDIO. --
					 * ----------------------
					 * ------------------------------------- -- REFERENCIAS: --
					 * --
					 * ---------------------------------------------------------
					 * -- CM = Cantidad del Movimiento. -- -- CT = Costo de
					 * Transferencia. -- -- CP = Costo Promedio Actual. -- -- EX
					 * = Existencia Actual. --
					 * ----------------------------------
					 * ------------------------- -- FORMULA: ( ( CM * CT ) + (
					 * CP * EX ) ) / ( EX + CM ); --
					 * ----------------------------
					 * -------------------------------
					 */
					vAvgCost = new BigDecimal(salesDetBean.getQuantity()
							* measureUnitBean.getQuantity());
					vAvgCost = new BigDecimal(vAvgCost.doubleValue()
							* salesDetBean.getNetCost().doubleValue());
//					vAvgCost = new BigDecimal(
//							vAvgCost.doubleValue()
//									+ (suplyCostStkBean.getAverageCost()
//											.doubleValue() * suplyCostStkBean
//											.getStock()));
//					/**
//					 * Podría dar el caso de que la cantidad existente fuese la
//					 * misma que la unidad básica en movimiento (transacción)
//					 * pero de signo contrario, dicho caso daría un valor cero.
//					 * Entonces tendríamos un error de división por cero
//					 */
//					if ((suplyCostStkBean.getStock() + (salesDetBean
//							.getQuantity() * measureUnitBean.getQuantity())) != 0) {
//						vAvgCost = new BigDecimal(
//								vAvgCost.doubleValue()
//										/ (suplyCostStkBean.getStock() + (salesDetBean
//												.getQuantity() * measureUnitBean
//												.getQuantity())));
//					}
//
//					suplyCostStkBean.setAverageCost(vAvgCost);
//					supSrv.updateSupplyCostStock(suplyCostStkBean);
//				}
			}

			/**
    		 * 
    		 */
		} catch (CommonException e) {
			System.out.println("error en feroz try catch ** ".concat(e
					.getMessage().toString()));
			log.error(e);
		}

	}

//	public void feesToCustomersProcess(SalesHeadBean salesHeadBean) {
//		System.out.println("Entramos en feesToCustomersProcess ** ");
//		Integer vCantCuo = new Integer(0);
//		System.out.println("## 1");
//		BigDecimal vAmountOfFee = new BigDecimal(0);
//		System.out.println("## 2");
//		BigDecimal vAmountOfFeeAc = new BigDecimal(0);
//		/**
//		 * traer los decimales de la moneda. traer numero de cuotas, periodo de
//		 * la tabla de condiciones de compra loopear por la cantidad de cuotas
//		 * que tenga la condicion de compra insertar un registro por cada loop
//		 */
//		try {
//			System.out.println("## 3");
//			CurrencyBean currencyBean = new CurrencyBean();
//			CurrencyServices crSrv = new CurrencyServices(this.sqlMap.getConfig());
//			currencyBean = crSrv.getCurrencyData(salesHeadBean.getCurrency());
//			System.out.println("## 4");
//			BuyConditionBean buyCondBean = new BuyConditionBean();
//			BuyConditionServices bcSrv = new BuyConditionServices(this.sqlMap.getConfig());
//			buyCondBean = bcSrv.getBuyConditionById(salesHeadBean.getBuyCondition());
//			System.out.println("## 5");
//
//			if (!buyCondBean.getInstalments().equals(0)) {
//				vAmountOfFee = salesHeadBean.getTotal().divide(
//						new BigDecimal(buyCondBean.getInstalments()), 0,
//						RoundingMode.HALF_UP);
//			} else {
//				vAmountOfFee = salesHeadBean.getTotal();
//			}
//
//			System.out.println("## 7");
//			String vTipo = new String("");
//
//			System.out.println("## 8");
//			if (buyCondBean.getInstalments().equals(0)) {
//				vTipo = "CONTADO";
//				vCantCuo = 0;
//			} else {
//				vTipo = "CREDITO";
//				vCantCuo = 1;
//			}
//			Date vEndDate = new Date();
//			vEndDate = salesHeadBean.getVoucherDate();
//
//			while (buyCondBean.getInstalments() >= vCantCuo) {
//
//				FeesToCustomersBean feesToCustomersBean = new FeesToCustomersBean();
//				FeesToCustomersServices feesToCustomersSrv = new FeesToCustomersServices(
//						this.sqlMap.getConfig());
//				System.out.println("## 6");
//				System.out.println("## dentro del while ** ");
//				// try {
//				System.out.println("dentro del while. getInstalments()" + buyCondBean.getInstalments() + " - vCantCuo= " + vCantCuo);
//				System.out.println("antes if. vAmountOfFee= " + vAmountOfFee + " - vAmountOfFeeAc= " + vAmountOfFeeAc);
//				if (buyCondBean.getInstalments().equals(vCantCuo)) {
//					System.out.println("buyCondBean.getInstalments() == (vCantCuo)");
//					vAmountOfFee = salesHeadBean.getTotal().subtract(vAmountOfFeeAc);
//				} else {
//					System.out.println("buyCondBean.getInstalments() != (vCantCuo)");
//					vAmountOfFeeAc = vAmountOfFeeAc.add(vAmountOfFee);
//				}
//				System.out.println("despues if. vAmountOfFee= " + vAmountOfFee + " - vAmountOfFeeAc= " + vAmountOfFeeAc);
//				System.out.println("## 9");
//				System.out.println("## 10");
//				feesToCustomersBean.setInsDate(DateAssistant.getHoleDateTime());
//				feesToCustomersBean.setInsDatetime(DateAssistant.getHoleDateTime());
//				System.out.println("## 12");
//				vEndDate = DateAssistant.getDatePlusDay(vEndDate, buyCondBean.getPeriod());
//				feesToCustomersBean.setEndDate(vEndDate);
//				feesToCustomersBean.setIdProv(salesHeadBean.getIdSupplier());
//				System.out.println("## 11");
//				feesToCustomersBean.setIdTrans(salesHeadBean.getId());
//				feesToCustomersBean.setIdTypeTrans(salesHeadBean.getIdTypeTrans());
//				System.out.println("## 13");
//				feesToCustomersBean.setInstalments((vTipo == "CONTADO") ? 0 : vCantCuo);
//				System.out.println("## 14");
//				feesToCustomersBean.setAmountOfFee(vAmountOfFee);
//				feesToCustomersBean.setBalanceOfFee(vAmountOfFee);
//				System.out.println("## 15");
//				feesToCustomersSrv.saveNewFeesToCustomers(feesToCustomersBean);
//				System.out.println("## 16");
//				feesToCustomersBean = null;
//				feesToCustomersSrv = null;
//				vCantCuo++;
//				System.out.println("## 17");
//				// } catch (ParseException e) {
//				// System.out.println("error insertando cuotas ** ".concat(e.getMessage().toString()+" error insertCuotas"));
//				// log.error(e);
//				// }
//				System.out.println("## 18");
//
//			}
//		} catch (CommonException e) {
//			System.out
//					.println("error CommonException primer try catch en procesa cuotas prov ** "
//							.concat(e.getMessage().toString()));
//			log.error(e);
//		} catch (ParseException e2) {
//			System.out.println("error ParseException primer try catch en procesa cuotas prov ** ".concat(e2.getMessage().toString()));
//			log.error(e2);
//		}
//	}

	public void cancelSales() throws SQLException {
		try {
			Boolean noneSelected = true;
			Iterator<SalesHeadBean> it = allSalesCancelHead.iterator();

			while (it.hasNext()) {
				SalesHeadBean next = it.next();
				if (next.getSelected() == true) {
					noneSelected = false;
					this.prSrv.cancelSale(next.getId());
				}
				if(!it.hasNext()){
					this.comAssist.generateInfoMsg(
							"Anulaci�n realizada con �xito!",
							"actionform:cancelSalesBtn");
				}
			}

			if (noneSelected == true) {
				this.comAssist.generateErrorMsg(
						"Favor seleccione al menos un registro",
						"actionform:cancelSalesBtn");
			} else {
				this.retrievePendingSales(this.getSaleCancelHead(),
						"CANCEL");
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}

	}

	// Retrieving data for updating
	public void dataToEdit(Long id) {
		System.out.println("id = ".concat(id.toString()));

	}

	public void dataToEditUpd() throws ParseException {

	}

	// falta el metodo void dataToDelete(Long id)

	// Getters and Setters

	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}

	public ParamHolder getParam() {
		return param;
	}

	public void setParam(ParamHolder param) {
		this.param = param;
	}

	public SalesHeadBean getSalesHead() {
		return salesHead;
	}

	public void setSalesHead(SalesHeadBean salesHead) {
		this.salesHead = salesHead;
	}

	public SalesDetBean getSalesDet() {
		return salesDet;
	}

	public void setSalesDet(SalesDetBean salesDet) {
		this.salesDet = salesDet;
	}

	public EditNumbers getNumbers() {
		return numbers;
	}

	public void setNumbers(EditNumbers numbers) {
		this.numbers = numbers;
	}

	public List<SalesDetBean> getAllSalesDet() {
		return allSalesDet;
	}

	public void setAllSalesDet(List<SalesDetBean> allSalesDet) {
		this.allSalesDet = allSalesDet;
	}

	public SalesHeadBean getSaleQueryHead() {
		return saleQueryHead;
	}

	public void setSaleQueryHead(SalesHeadBean saleQueryHead) {
		this.saleQueryHead = saleQueryHead;
	}

	public SalesDetBean getSaleQueryDet() {
		return saleQueryDet;
	}

	public void setSaleQueryDet(SalesDetBean saleQueryDet) {
		this.saleQueryDet = saleQueryDet;
	}

	public Collection<SalesHeadBean> getAllSalesQueryHead() {
		return allSalesQueryHead;
	}

	public void setAllSalesQueryHead(Collection<SalesHeadBean> allSalesQueryHead) {
		this.allSalesQueryHead = allSalesQueryHead;
	}

	public Collection<SalesDetBean> getAllSalesQueryDet() {
		return allSalesQueryDet;
	}

	public void setAllSalesQueryDet(Collection<SalesDetBean> allSalesQueryDet) {
		this.allSalesQueryDet = allSalesQueryDet;
	}

	public SalesHeadBean getSaleCancelHead() {
		return saleCancelHead;
	}

	public void setSaleCancelHead(SalesHeadBean saleCancelHead) {
		this.saleCancelHead = saleCancelHead;
	}

	public SalesDetBean getSaleCancelDet() {
		return saleCancelDet;
	}

	public void setSaleCancelDet(SalesDetBean saleCancelDet) {
		this.saleCancelDet = saleCancelDet;
	}

	public Collection<SalesHeadBean> getAllSalesCancelHead() {
		return allSalesCancelHead;
	}

	public void setAllSalesCancelHead(Collection<SalesHeadBean> allSalesCancelHead) {
		this.allSalesCancelHead = allSalesCancelHead;
	}

	public Collection<SalesDetBean> getAllSalesCancelDet() {
		return allSalesCancelDet;
	}

	public void setAllSalesCancelDet(Collection<SalesDetBean> allSalesCancelDet) {
		this.allSalesCancelDet = allSalesCancelDet;
	}

	public SalesHeadBean getSaleConfHead() {
		return saleConfHead;
	}

	public void setSaleConfHead(SalesHeadBean saleConfHead) {
		this.saleConfHead = saleConfHead;
	}

	public SalesDetBean getSaleConfDet() {
		return saleConfDet;
	}

	public void setSaleConfDet(SalesDetBean saleConfDet) {
		this.saleConfDet = saleConfDet;
	}

	public Collection<SalesHeadBean> getAllSalesConfHead() {
		return allSalesConfHead;
	}

	public void setAllSalesConfHead(Collection<SalesHeadBean> allSalesConfHead) {
		this.allSalesConfHead = allSalesConfHead;
	}

	public Collection<SalesDetBean> getAllSalesConfDet() {
		return allSalesConfDet;
	}

	public void setAllSalesConfDet(Collection<SalesDetBean> allSalesConfDet) {
		this.allSalesConfDet = allSalesConfDet;
	}

	public FeesToCustomersBean getFeesToCustomersQuery() {
		return feesToCustomersQuery;
	}

	public void setFeesToCustomersQuery(FeesToCustomersBean feesToCustomersQuery) {
		this.feesToCustomersQuery = feesToCustomersQuery;
	}

	public Collection<FeesToCustomersBean> getAllFeesToCustomersQuery() {
		return allFeesToCustomersQuery;
	}

	public void setAllFeesToCustomersQuery(
			Collection<FeesToCustomersBean> allFeesToCustomersQuery) {
		this.allFeesToCustomersQuery = allFeesToCustomersQuery;
	}

	public static Boolean getCanSave() {
		return canSave;
	}

	public static void setCanSave(Boolean canSave) {
		TrnSale.canSave = canSave;
	}

	public String getOperationType() {
		return operationType;
	}

	public void setOperationType(String operationType) {
		this.operationType = operationType;
	}

	public Boolean getValidateEntireForm() {
		return validateEntireForm;
	}

	public void setValidateEntireForm(Boolean validateEntireForm) {
		this.validateEntireForm = validateEntireForm;
	}

	public modalSelectHolder getSelectHolder() {
		return selectHolder;
	}

	public void setSelectHolder(modalSelectHolder selectHolder) {
		this.selectHolder = selectHolder;
	}

	public HtmlDatascroller getScroller() {
		return scroller;
	}

	public void setScroller(HtmlDatascroller scroller) {
		this.scroller = scroller;
	}

	public Integer getScrollerPage() {
		return scrollerPage;
	}

	public void setScrollerPage(Integer scrollerPage) {
		this.scrollerPage = scrollerPage;
	}

	public Boolean getSelectedAll() {
		return selectedAll;
	}

	public void setSelectedAll(Boolean selectedAll) {
		this.selectedAll = selectedAll;
	}

	public UsersBean getUser() {
		return user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}

	


	
	
	
}
